<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, onBeforeMount } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useServerStore } from '@/stores/server'
import ServerCard from '@/components/server/ServerCard.vue'
import ServerFilter from '@/components/server/ServerFilter.vue'
import type { Server } from '@/types/server'

// 接收props
const props = defineProps<{
  filter?: string
}>()

const route = useRoute()
const router = useRouter()
const serverStore = useServerStore()
serverStore.pageSize = 9 // 设置每页加载9条记录
const loading = ref(false)
const initialLoading = ref(true) // 初始加载状态
const error = ref<string | null>(null)
const allServers = ref<Server[]>([])
const noMoreData = ref(false)
const animatedIndex = ref(-1) // 控制卡片动画

// 过滤器状态
const activeFilter = ref('all') // 默认显示全部
const searchText = ref('') // 搜索文本

// 读取路由属性或URL参数设置初始过滤器和搜索文本
onBeforeMount(() => {
  // 首先检查组件props
  if (props.filter) {
    activeFilter.value = props.filter
    applyFilterFromTag(props.filter)
  } 
  // 其次检查URL查询参数
  else if (route.query.filter) {
    const queryFilter = route.query.filter as string
    activeFilter.value = queryFilter
    applyFilterFromTag(queryFilter)
  }
  
  // 检查URL中是否有搜索文本
  if (route.query.search) {
    searchText.value = route.query.search as string
    // 注意：这里不使用 setSearchText 方法，而是直接设置 searchQuery 属性
    if (serverStore.searchQuery !== undefined) {
      serverStore.searchQuery = searchText.value
    }
  }
})

// 应用标签过滤器
const applyFilterFromTag = (filter: string) => {
  // 重置所有过滤条件
  serverStore.resetFilters()
  
  switch(filter) {
    case 'hot':
      // 热门：标签中包含"热门"
      serverStore.addTag('热门')
      break
    case 'community':
      // 社区：is_internal = false
      serverStore.setIsInternal(false)
      break
    case 'internal':
      // 内部：is_internal = true
      serverStore.setIsInternal(true)
      break
    case 'huawei_online':
      serverStore.setAccessMode("huawei_online")
      break
    case 'all':
    default:
      // 全部：不设置特殊过滤
      break
  }
  
  // 如果有搜索文本，保留搜索条件
  if (searchText.value && serverStore.searchQuery !== undefined) {
    serverStore.searchQuery = searchText.value
  }
}

// 切换过滤器
const switchFilter = (filter: string) => {
  activeFilter.value = filter
  applyFilterFromTag(filter)
  
  // 更新URL，保留搜索文本参数
  const query = { ...route.query, filter }
  if (searchText.value) {
    query.search = searchText.value
  }
  
  // 使用replace代替push，避免创建大量历史记录
  router.replace({ query })
  
  // 重置数据状态
  serverStore.setPage(1)
  allServers.value = []
  noMoreData.value = false
  
  // 手动触发数据加载
  initialLoading.value = true
  loadServers(true)
}

// 加载 Server 列表
const loadServers = async (isInitialLoad = false) => {
  if ((loading.value && !isInitialLoad) || noMoreData.value) return
  
  if (isInitialLoad) {
    initialLoading.value = true
    // 初始加载时始终重置列表状态
    serverStore.setPage(1)
    allServers.value = []
    noMoreData.value = false
  } else {
    loading.value = true
  }
  error.value = null
  
  try {
    if (isInitialLoad) {
      // 已经在上面重置了状态
    }
    
    const result = await serverStore.fetchServers()
    
    // 将新数据追加到当前列表
    if (result && result.length > 0) {
      const startIndex = allServers.value.length
      allServers.value = [...allServers.value, ...result]
      
      // 触发卡片入场动画
      animateCards(startIndex)
    }
    
    // 检查是否还有更多数据
    if (allServers.value.length >= serverStore.totalCount) {
      noMoreData.value = true
    }
  } catch (err: any) {
    console.error('加载失败:', err)
    error.value = err.message || '获取 Server 列表失败'
  } finally {
    if (isInitialLoad) {
      initialLoading.value = false
    }
    loading.value = false
  }
}

// 卡片动画
const animateCards = (startIndex: number) => {
  let delay = 0
  for (let i = startIndex; i < allServers.value.length; i++) {
    setTimeout(() => {
      animatedIndex.value = i
    }, delay)
    delay += 100
  }
}

// 处理滚动到底部加载更多
const handleScroll = () => {
  const scrollPosition = window.scrollY + window.innerHeight
  const documentHeight = document.documentElement.scrollHeight
  
  // 当滚动到距离底部200px时，加载更多数据
  if (scrollPosition >= documentHeight - 200 && !loading.value && !noMoreData.value && !initialLoading.value) {
    console.log('触发滚动加载, 当前页码:', serverStore.currentPage)
    // 增加页码
    serverStore.setPage(serverStore.currentPage + 1)
    loadServers()
  }
}

// 处理筛选
const handleFilter = (newSearchText?: string) => {  
  // 如果提供了新的搜索文本，更新搜索文本
  if (newSearchText !== undefined) {
    searchText.value = newSearchText
    
    // 更新URL中的搜索参数
    const query = { ...route.query }
    if (searchText.value) {
      query.search = searchText.value
    } else {
      delete query.search
    }
    
    // 使用replace更新URL，避免创建大量历史记录
    router.replace({ query })
    
    // 更新store中的搜索查询
    if (serverStore.searchQuery !== undefined) {
      serverStore.searchQuery = searchText.value
    }
  }
  
  serverStore.setPage(1)
  allServers.value = []
  noMoreData.value = false
  
  // 手动触发数据加载
  initialLoading.value = true
  loadServers(true) // 重置并重新加载
}

// 监听store中servers的变化（用于调试）
watch(() => serverStore.servers, (newVal) => {
  // console.log('store中 Server 数据变化:', newVal)
})

// 初始加载
onMounted(() => {
  loadServers(true)
  window.addEventListener('scroll', handleScroll)
})

// 清理事件监听
onUnmounted(() => {
  window.removeEventListener('scroll', handleScroll)
})

// 获取卡片动画类
const getCardAnimationClass = (index: number) => {
  return index <= animatedIndex.value ? 'animate-fade-in-up visible' : 'invisible opacity-0'
}

// 返回按钮处理
const goBack = () => {
  router.push('/') // 返回首页
}
</script>

<template>
  <div>
    <!--  Server 筛选组件 -->
    <div class="bg-white dark:bg-gray-800 rounded-lg shadow-md p-6 mb-8 transition-all duration-300 hover:shadow-lg border border-gray-100 dark:border-gray-700">
      <!-- 返回按钮 -->
      <div class="mb-5">
        <button @click="goBack" class="inline-flex items-center text-gray-600 dark:text-gray-400 hover:text-primary-600 dark:hover:text-primary-400 transition-colors duration-300 group">
          <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5 mr-2 group-hover:-translate-x-1 transition-transform duration-300" viewBox="0 0 20 20" fill="currentColor">
            <path fill-rule="evenodd" d="M9.707 16.707a1 1 0 01-1.414 0l-6-6a1 1 0 010-1.414l6-6a1 1 0 011.414 1.414L5.414 9H17a1 1 0 110 2H5.414l4.293 4.293a1 1 0 010 1.414z" clip-rule="evenodd" />
          </svg>
          <span class="font-medium">返回首页</span>
        </button>
      </div>
      <ServerFilter @filter="handleFilter" :initial-search-text="searchText" />
      
      <!-- 过滤标签栏 -->
      <div class="mt-6 flex flex-wrap items-center gap-4">
        <button 
          @click="switchFilter('all')" 
          class="px-5 py-2 rounded-full text-sm font-medium transition-all duration-300 shadow-sm"
          :class="activeFilter === 'all' 
            ? 'bg-primary-100 text-primary-800 dark:bg-primary-900 dark:text-primary-200 border-primary-500 transform scale-105' 
            : 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 hover:scale-105'"
        >
          <span class="flex items-center">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5" viewBox="0 0 20 20" fill="currentColor">
              <path d="M7 3a1 1 0 000 2h6a1 1 0 100-2H7zM4 7a1 1 0 011-1h10a1 1 0 110 2H5a1 1 0 01-1-1zM2 11a2 2 0 012-2h12a2 2 0 012 2v4a2 2 0 01-2 2H4a2 2 0 01-2-2v-4z" />
            </svg>
            全部
          </span>
        </button>
        <button 
          @click="switchFilter('hot')" 
          class="px-5 py-2 rounded-full text-sm font-medium transition-all duration-300 shadow-sm"
          :class="activeFilter === 'hot' 
            ? 'bg-red-100 text-red-800 dark:bg-red-900 dark:text-red-200 border-red-500 transform scale-105' 
            : 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 hover:scale-105'"
        >
          <span class="flex items-center">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M12.395 2.553a1 1 0 00-1.45-.385c-.345.23-.614.558-.822.88-.214.33-.403.713-.57 1.116-.334.804-.614 1.768-.84 2.734a31.365 31.365 0 00-.613 3.58 2.64 2.64 0 01-.945-1.067c-.328-.68-.398-1.534-.398-2.654A1 1 0 005.05 6.05 6.981 6.981 0 003 11a7 7 0 1011.95-4.95c-.592-.591-.98-.985-1.348-1.467-.363-.476-.724-1.063-1.207-2.03zM12.12 15.12A3 3 0 017 13s.879.5 2.5.5c0-1 .5-4 1.25-4.5.5 1 .786 1.293 1.371 1.879A2.99 2.99 0 0113 13a2.99 2.99 0 01-.879 2.121z" clip-rule="evenodd" />
            </svg>
            热门
          </span>
        </button>
        <button 
          @click="switchFilter('internal')" 
          class="px-5 py-2 rounded-full text-sm font-medium transition-all duration-300 shadow-sm"
          :class="activeFilter === 'internal' 
            ? 'bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200 border-purple-500 transform scale-105' 
            : 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 hover:scale-105'"
        >
          <span class="flex items-center">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M2.166 4.999A11.954 11.954 0 0010 1.944 11.954 11.954 0 0017.834 5c.11.65.166 1.32.166 2.001 0 5.225-3.34 9.67-8 11.317C5.34 16.67 2 12.225 2 7c0-.682.057-1.35.166-2.001zm11.541 3.708a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd" />
            </svg>
            华为内部
          </span>
        </button>
        <button 
          @click="switchFilter('huawei_online')" 
          class="px-5 py-2 rounded-full text-sm font-medium transition-all duration-300 shadow-sm"
          :class="activeFilter === 'huawei_online' 
            ? 'bg-teal-100 text-teal-800 dark:bg-teal-900 dark:text-teal-200 border-teal-500 transform scale-105' 
            : 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 hover:scale-105'"
        >
          <span class="flex items-center">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5" viewBox="0 0 20 20" fill="currentColor">
              <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm1-12a1 1 0 10-2 0v4a1 1 0 00.293.707l2.828 2.829a1 1 0 101.415-1.415L11 9.586V6z" clip-rule="evenodd" />
            </svg>
            内部-在线
          </span>
        </button>
        <button 
          @click="switchFilter('community')" 
          class="px-5 py-2 rounded-full text-sm font-medium transition-all duration-300 shadow-sm"
          :class="activeFilter === 'community' 
            ? 'bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200 border-blue-500 transform scale-105' 
            : 'bg-gray-100 text-gray-700 dark:bg-gray-700 dark:text-gray-300 hover:bg-gray-200 dark:hover:bg-gray-600 hover:scale-105'"
        >
          <span class="flex items-center">
            <svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5" viewBox="0 0 20 20" fill="currentColor">
              <path d="M13 6a3 3 0 11-6 0 3 3 0 016 0zM18 8a2 2 0 11-4 0 2 2 0 014 0zM14 15a4 4 0 00-8 0v3h8v-3zM6 8a2 2 0 11-4 0 2 2 0 014 0zM16 18v-3a5.972 5.972 0 00-.75-2.906A3.005 3.005 0 0119 15v3h-3zM4.75 12.094A5.973 5.973 0 004 15v3H1v-3a3 3 0 013.75-2.906z" />
            </svg>
            社区
          </span>
        </button>
      </div>
    </div>
    
    <!-- 初始加载状态 -->
    <div v-if="initialLoading" class="flex flex-col items-center justify-center min-h-[300px]">
      <div class="relative">
        <div class="w-16 h-16 border-4 border-primary-200 border-t-primary-500 rounded-full animate-spin"></div>
        <div class="absolute top-0 left-0 w-16 h-16 border-4 border-transparent border-r-secondary-500 rounded-full animate-spin-slow"></div>
      </div>
      <p class="mt-4 text-gray-600 dark:text-gray-300 text-lg">正在加载 Server 列表...</p>
    </div>
    
    <!-- 错误信息 -->
    <div v-else-if="error" class="bg-red-50 dark:bg-red-900/30 border-l-4 border-red-500 p-6 rounded-md my-6 shadow-lg animate-fade-in">
      <div class="flex items-start">
        <div class="flex-shrink-0">
          <svg class="h-6 w-6 text-red-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
          </svg>
        </div>
        <div class="ml-3">
          <h3 class="text-lg font-medium text-red-800 dark:text-red-300">加载失败</h3>
          <p class="mt-2 text-red-700 dark:text-red-200">{{ error }}</p>
          <button @click="loadServers(true)" class="mt-4 px-4 py-2 bg-red-600 hover:bg-red-700 text-white rounded-md shadow transition-colors duration-300">
            重试
          </button>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-else-if="allServers.length === 0 && !initialLoading" class="text-center my-12 py-16 bg-gray-50 dark:bg-gray-800/50 rounded-lg shadow-inner animate-fade-in">
      <div class="max-w-md mx-auto">
        <svg xmlns="http://www.w3.org/2000/svg" class="h-20 w-20 mx-auto mb-6 text-gray-400 dark:text-gray-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M9.172 16.172a4 4 0 015.656 0M9 10h.01M15 10h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
        <p class="text-2xl font-bold text-gray-700 dark:text-gray-200 mb-2">未找到匹配的MCP Server </p>
        <p class="text-gray-600 dark:text-gray-400 mb-6">尝试调整搜索条件或重置过滤器</p>
      </div>
    </div>
    
    <!--  Server 列表 -->
    <div v-else>
      <!-- 列表 -->
      <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
        <div 
          v-for="(server, index) in allServers" 
          :key="server.id" 
          class="h-full transition-all duration-500 transform"
          :class="getCardAnimationClass(index)"
        >
          <ServerCard :server="server" />
        </div>
      </div>
      
      <!-- 加载更多提示 -->
      <div class="text-center my-8">
        <div v-if="loading" class="py-4">
          <div class="inline-flex items-center px-4 py-2 bg-primary-100 dark:bg-primary-900 rounded-full">
            <div class="animate-spin rounded-full h-5 w-5 border-b-2 border-primary-500 mr-3"></div>
            <span class="text-primary-700 dark:text-primary-300">加载更多...</span>
          </div>
        </div>
        <p 
          v-else-if="noMoreData" 
          class="text-gray-500 dark:text-gray-400 py-4 border-t border-gray-200 dark:border-gray-700 mt-6"
        >
          — 已显示全部 {{ allServers.length }} 条数据 —
        </p>
        <button 
          v-else 
          @click="loadServers()" 
          class="mt-6 px-6 py-2 bg-gray-100 hover:bg-gray-200 dark:bg-gray-800 dark:hover:bg-gray-700 rounded-full text-gray-700 dark:text-gray-300 transition-colors duration-300"
        >
          点击加载更多
        </button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.bg-pattern {
  background-image: url("data:image/svg+xml,%3Csvg width='60' height='60' viewBox='0 0 60 60' xmlns='http://www.w3.org/2000/svg'%3E%3Cg fill='none' fill-rule='evenodd'%3E%3Cg fill='%23ffffff' fill-opacity='0.2'%3E%3Cpath d='M36 34v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zm0-30V0h-2v4h-4v2h4v4h2V6h4V4h-4zM6 34v-4H4v4H0v2h4v4h2v-4h4v-2H6zM6 4V0H4v4H0v2h4v4h2V6h4V4H6z'/%3E%3C/g%3E%3C/g%3E%3C/svg%3E");
}

.animate-spin-slow {
  animation: spin 3s linear infinite;
}

.animate-fade-in-up {
  animation: fadeInUp 0.6s ease-out forwards;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style> 